/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ctrl;

import model.AddRoomTypeBackingBean;
import entities.RoomType;
import hotel.jpa.IJpaCtrl;
import hotel.jpa.RoomTypeJpaCtrl;
import java.util.ArrayList;
import java.util.List;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.application.Application;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author Robin
 */
@ManagedBean(name = "addRoomTypeControllerBean")
public class AddRoomTypeControllBean {

    protected List<AddRoomTypeBackingBean> roomType = new ArrayList<AddRoomTypeBackingBean>();

    public void addRoomType() {

        //Get connection to database 
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hotel_pu");
        IJpaCtrl roomCtrl = new RoomTypeJpaCtrl(null, emf);

        //Using other bean (addRoomBackingBean)
        FacesContext ctx = FacesContext.getCurrentInstance();
        Application app = ctx.getApplication();
        ELContext ectx = ctx.getELContext();
        ExpressionFactory ef = app.getExpressionFactory();
        ValueExpression ve = ef.createValueExpression(ectx, "#{addRoomTypeBackingBean}", AddRoomTypeBackingBean.class);
        AddRoomTypeBackingBean db = (AddRoomTypeBackingBean) ve.getValue(ectx);

        //Creates the new room
        RoomType r = null;
        r = new RoomType(db.getNrOfBeds(), db.getName());

        List<RoomType> types = roomCtrl.findEntities();

        if (types.isEmpty()) {
            roomCtrl.create(r);
        } else {
            int i=0;
            boolean done = false;
            while(i < types.size() && done == false) {
                if(types.get(i).getName().equals(r.getName())){
                    
                }else{
                    roomCtrl.create(r);
                    done = true;
                }
                i++;
            }
        }


    }

    public List<AddRoomTypeBackingBean> getRoomType() {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hotel_pu");
        IJpaCtrl typeCtrl = new RoomTypeJpaCtrl(null, emf);

        roomType = typeCtrl.findEntities();

        return roomType;
    }

    public void setRoomType(List<AddRoomTypeBackingBean> roomType) {
        this.roomType = roomType;
    }
}
